package com.aote.util;

import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;

public class HttpPlugin {

	private static Logger log = Logger.getLogger(HttpPlugin.class);

	public JSONObject post(String url, JSONObject data) throws Exception {
		log.debug("url :" + url);
		log.debug("data :" + data);
		JSONObject ret = new JSONObject();
		HttpPost hp = new HttpPost(url);
		hp.setHeader("Content-Type", "application/JSON");
		hp.setEntity(new StringEntity(data.toString(), "UTF-8"));

		HttpClient httpClient = new DefaultHttpClient();
		HttpResponse response = httpClient.execute(hp);

		int code = response.getStatusLine().getStatusCode();
		log.debug("状态码"+code);
		if (code == 200) {
			log.debug("返回数据"+response.getEntity());
			String result = EntityUtils.toString(response.getEntity(), "UTF-8");
			log.debug("返回内容"+result);
			if (result.startsWith("{")){
				ret = new JSONObject(result);
				log.debug(ret);
				log.debug(new String(ret.toString()));
			}
		}

		log.debug("返回码: " + ret.toString());
		return ret;
	}
	public static JSONObject get(String path) {
		JSONObject accob = null ;
		try {
			DefaultHttpClient httpclient = new DefaultHttpClient();
			HttpGet getReqacc = new HttpGet(path);
			HttpResponse httpResacc = httpclient.execute(getReqacc);
			int code = httpResacc.getStatusLine().getStatusCode();
			if (code == 200) {
				HttpEntity accent = httpResacc.getEntity();
				if (accent !=null) {
					String accentstr = EntityUtils.toString(accent, "utf-8");
					 accob = new JSONObject(accentstr);
					return accob;
				}else {
					return new JSONObject();
				}
			}else {
				return new JSONObject();
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			return new JSONObject();
		}

		
	}
}
